/* 权限拦截 */
// import store from '@/store'
import { Router, RouteLocationNormalized, NavigationGuardNext, RouteRecordRaw } from 'vue-router'
import { useUserStore } from '@/store/modules/user'
import { usePermissionsStore } from '@/store/modules/permissions'
import router from '@/router'

export default function createPermissionGuard (router:Router) {
  // 添加前置守卫
  router.beforeEach(routerBeforeEachFunc)
}

// 白名单
const whiteList = ['/login']

/** 全局前置守卫 */
async function routerBeforeEachFunc (to:RouteLocationNormalized, from:RouteLocationNormalized, next:NavigationGuardNext) {
  const userStore = useUserStore()
  const permissionsStore = usePermissionsStore()

  const token = userStore.$state.token
  if (token) {
    const roles = userStore.roles
    if (roles.length === 0 || permissionsStore.routes.length === 0) {
      // 无权限
      try {
        const userinfo = await userStore.getUserInfo() // 获取用户信息
        const roles = userinfo?.roles || []
        const routes = await permissionsStore.getRoutes(roles) // 创建权限路由
        // 动态创建路由
        routes.forEach((route) => {
          router.addRoute(route)
        })

        // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
        next({ path: to.fullPath, replace: true, query: to.query })
      } catch (error) {
        // 权限建立失败
        userStore.loginout()
        next('/login')
      }
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      // 白名单中 可以无权限访问
      return next()
    } else {
      // 未登录 跳转登录
      next('/login')
    }
  }
}

// 全局后置守卫
